#include <iostream>
#include <vector>
#define mod 20123
using namespace std;




int main(){
	int ans=0;
	int n,m;
	cin>>n>>m;
	int next[n][m];
	vector<int> stair[n];
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			int s;
			cin>>s>>next[i][j];
			if(s == 1)
				stair[i].push_back(j);
		}
	}
	
	int index;
	cin>>index;
	
	
	for(int k=0;k<n;k++){
		ans += next[k][index];
		ans %= mod;
		int room=0;
		for(int i=0;i<stair[k].size();i++){
			if(stair[k][i] >= index){
				room = i;
				break;
			}
		}
		room = (room+next[k][index]-1)%stair[k].size();
		index = stair[k][room];
	}
	
	cout<<ans;
	return 0;
}

/*
3 3
0 2
1 3
0 1
1 1
1 2
0 1
0 1
1 2
0 3
2
*/
